package com.grantz.function.bbs.core.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.grantz.function.bbs.core.entity.DiscussChild;
import com.grantz.function.bbs.core.entity.GroupDetail;
import com.grantz.function.bbs.core.inter.DiscussChildService;
import com.grantz.function.bbs.core.jpa.DiscussChildJPA;
import com.grantz.model.bbs.DiscussChildModel;
import com.grantz.model.bbs.DiscussChildSearch;
import com.grantz.model.bbs.GroupDetailModel;
import com.grantz.models.base.element.page.ElementPage;

@Service
public class DiscussChildServiceImpl implements DiscussChildService {

	@Autowired
	private DiscussChildJPA dao;

	@Override
	public ElementPage<DiscussChildModel> queryElementPage(DiscussChildSearch query) throws Exception {
		Page<DiscussChild>  page = queryPage(query);
		return new ElementPage<DiscussChildModel>(popList(page.getContent()), page.getTotalElements(), page.getNumber(), page.getSize());
	}
	
	private  List<DiscussChildModel>  popList(List<DiscussChild>  entityList){
		List<DiscussChildModel>  rt = new ArrayList<DiscussChildModel>();
		DiscussChildModel  model = null ;
		for(DiscussChild  entity : entityList) {
			  model =  new DiscussChildModel();
			  model.setId(entity.getId());
			  rt.add(model);
		}
		return rt;
	}

	@Override
	public Optional<DiscussChild> findOneById(String id) {
		return dao.findById(id);
	}

	@Override
	public DiscussChild save(DiscussChild entity) {
		return dao.save(entity);
	}

	@Override
	public Page<DiscussChild> queryPage(DiscussChildSearch model) throws Exception {
		PageRequest pageable = PageRequest.of(model.getPageNo(), model.getPageSize());
		Specification<DiscussChild> specifications = new Specification<DiscussChild>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<DiscussChild> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
//				if(StringUtil.isNotEmpty(model.getWechatno())) {
//					Predicate pred = criteriaBuilder.like(root.get("wechatNo").as(String.class), "%"+model.getWechatno()+"%");
//					list.add(pred);
//				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		return dao.findAll(specifications, pageable);
	}
}
